const Router = require("koa-router");
const User = require("./db/schemas/user");
const Jwt = require("./utils/jwt");
const uuid = require("uuid");

const router = new Router();

router.get("/", (ctx) => {
  ctx.body = "/";
});

router.post("/login", async (ctx) => {
  const { username, password } = ctx.request.body;
  const user = await User.findOne({ username }).exec();

  if (user && user.password == password) {
    ctx.body = {
      code: 0,
      message: "登陆成功",
      data: {
        token: Jwt.getToken({ username, uuid: user.uuid }),
      },
    };
  } else {
    ctx.body = {
      code: 2,
      message: "账号或密码错误",
    };
  }
});

router.post("/register", async (ctx) => {
  const { username, password } = ctx.request.body;
  const result = await User.findOne({ username }).exec();
  if (result) {
    ctx.body = {
      code: 1,
      message: "用户名已存在",
    };
  } else {
    const user = new User({ username, password, uuid: uuid.v4() });
    user.save();
    ctx.body = {
      code: 0,
      message: "注册成功",
    };
  }
});

// 登出
router.get("/logout", async (ctx) => {
  const { authorization: token = "" } = ctx.request.headers;
  const userInfo = Jwt.verify(token);
  if (userInfo) {
    const user = await User.findOne({ username: userInfo.username }).exec();
    user.uuid = uuid.v4();
    user.save();
    ctx.body = {
      code: 0,
      message: "用户已登出",
    };
  } else {
    ctx.body = {
      code: 1005,
      message: "登出失败",
    };
  }
});

// IDP获取用户信息
router.get("/user-info", async (ctx) => {
  const { authorization: token = "" } = ctx.request.headers;
  const userInfo = Jwt.verify(token);
  const { username } = userInfo || {};
  const user = await User.findOne({ username }).exec();

  if (userInfo && user && userInfo.uuid == user.uuid) {
    ctx.body = {
      code: 0,
      message: "用户已在登录态",
      data: userInfo,
    };
  } else {
    ctx.body = {
      code: 1001,
      message: "用户未登录",
      data: null,
    };
  }
});

module.exports = router;
